package com.journaldev.spring.util;

import java.beans.PropertyEditorSupport;
import java.util.HashSet;
import java.util.Set;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.journaldev.spring.model.Medicine;
import com.journaldev.spring.model.PrescriptionMedicine;
import com.journaldev.spring.service.MedicineService;

public class SimplePrescriptionMedicineEditor extends PropertyEditorSupport {

	private MedicineService medService;
	
	public SimplePrescriptionMedicineEditor(MedicineService medService) {
		this.medService = medService;
	}
	
	public SimplePrescriptionMedicineEditor() {
		
	}
	
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		
		Set<PrescriptionMedicine> prescriptionMedicine = new HashSet<PrescriptionMedicine>();
        try {
        	JsonElement jelement = new JsonParser().parse(text);
            JsonObject  jobject = jelement.getAsJsonObject();
            JsonArray jarray = jobject.getAsJsonArray("data");
            for(int i = 0; i < jarray.size(); i++){
            	JsonObject item = jarray.get(i).getAsJsonObject();
                int medicineId = item.get("id").getAsInt();
                int number = item.get("soluong").getAsInt();
                String howToUse = item.get("cachsudung").getAsString();
            	// get medicine object with id
                Medicine med = medService.getMedicineById(medicineId);
                // now do something with the Object
                if(med != null) {
                	PrescriptionMedicine tmPresMed = new PrescriptionMedicine();
                	tmPresMed.setMedicine(med);
                	tmPresMed.setSoluong(number);
                	tmPresMed.setCachsudung(howToUse);
                	tmPresMed.setPrescription(null);
                	prescriptionMedicine.add(tmPresMed);
                }
            }
            //System.out.println("User info :" + presMedicine.getWardName());
        } catch (NumberFormatException ex) {
            System.out.println(ex);
        }
        setValue(prescriptionMedicine);
	}
	
}
